﻿using System.Collections.Generic;
using System.Windows.Input;
using Microsoft.Expression.Interactivity.Core;

namespace TheMovieDb.Example.ViewModels
{
    public class PersonViewModel : ViewModelBase
    {
        private string _searchText;
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value;
                RaisePropertyChanged("SearchText");
            }
        }

        private IEnumerable<TmdbPerson> _persons;
        public IEnumerable<TmdbPerson> Persons
        {
            get { return _persons; }
            set { _persons = value;
                RaisePropertyChanged("Persons");
            }
        }

        private TmdbPerson _selectedPerson;
        public TmdbPerson SelectedPerson
        {
            get { return _selectedPerson; }
            set { _selectedPerson = value;
                RaisePropertyChanged("SelectedPerson");
                if(value != null)
                {
                    IsBusy = true;
                    _api.GetPersonInfoAsync(value.Id);
                }
            }
        }

        private TmdbPerson _person;
        public TmdbPerson Person
        {
            get { return _person; }
            set { _person = value;
                RaisePropertyChanged("Person");
            }
        }

        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }

        public ICommand SearchCommand { get; set; }

        private readonly TmdbApi _api = new TmdbApi("");

        public PersonViewModel()
        {
            SearchCommand = new ActionCommand(Search);
            _api.PersonSearchCompleted += ApiPersonSearchCompleted;
            _api.GetPersonInfoCompleted += ApiGetPersonInfoCompleted;
        }

        void ApiGetPersonInfoCompleted(object sender, TmdbPersonInfoCompletedEventArgs e)
        {
            Person = e.Person;
            IsBusy = false;
        }

        void ApiPersonSearchCompleted(object sender, TmdbPersonSearchCompletedEventArgs e)
        {
            Persons = e.People;
            IsBusy = false;
        }

        public void Search()
        {
            if (string.IsNullOrEmpty(SearchText))
                return;

            IsBusy = true;
            _api.PersonSearchAsync(SearchText);
        }
    }
}
